package com.colin.juc.cas;

/**
 * Created by Colin on 2020/4/21 20:01
 * email: colinzhaodong@gmail.com
 * desc: 模拟CAS操作
 *
 * @author zhaod
 */
public class TwoThreadsCompetition implements Runnable{
	private volatile int value;

	public synchronized int compareAndSwap(int expectedValue,int newValue){
		int oldValue = value;
		if (expectedValue == oldValue){
			value = newValue;
		}
		return value;
	}

	public static void main(String[] args) throws InterruptedException {
		TwoThreadsCompetition r = new TwoThreadsCompetition();
		r.value = 0;
		Thread t1 = new Thread(r,"Thread 1");
		Thread t2 = new Thread(r,"Thread 2");
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println(r.value);
	}

	@Override
	public void run() {
		compareAndSwap(0,1);
	}
}
